﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using WMS.Common;
using WMS.Common.Minio;
using WMS.Model;
using WMS.Repository.IRepository;
using WMS.Service.IService;
using WMS.Service.Minio;
using WMS.Service.Redis;

namespace WMS.Service
{
    public class AvatarService : BaseServices<AvatarModel>, IAvatarService
    {
        private readonly IAvatarRepository _avatarRepository;
        private readonly IMinioService _minioService;
        private readonly IRedisService _redisService;
        private readonly ILogger<AvatarService> _logger;
        private readonly IUnitOfWork _unitOfWork;
        
        // 固定的默认头像地址
        private const string DEFAULT_AVATAR_URL = "http://127.0.0.1:9000/image/b_2100a4bf6b1f6cc166accefcc64571af.jpg";

        public AvatarService(IAvatarRepository avatarRepository,
                           IBaseRepository<AvatarModel> repository,
                           ILogger<BaseServices<AvatarModel>> logger,
                           IMinioService minioService,
                           IRedisService redisService,
                           IUnitOfWork unitOfWork,
                           ILogger<AvatarService> avatarLogger) : base(repository, logger)
        {
            _avatarRepository = avatarRepository;
            _minioService = minioService;
            _redisService = redisService;
            _logger = avatarLogger;
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 根据用户编码获取头像URL
        /// </summary>
        public async Task<string> GetAvatarUrlByUserCodeAsync(string userCode)
        {
            // Redis缓存键
            var cacheKey = $"avatar:url:{userCode}";

            try
            {
                // 先从Redis获取缓存
                var cachedUrl = await _redisService.GetStringAsync(cacheKey);
                if (!string.IsNullOrEmpty(cachedUrl))
                {
                    _logger.LogDebug($"从Redis缓存获取头像URL: {userCode}");
                    return cachedUrl;
                }

                // 缓存不存在，从数据库查询
                var fileStorage = await _avatarRepository.GetAvatarByUserCodeAsync(userCode);

                string avatarUrl;

                if (fileStorage != null && !string.IsNullOrEmpty(fileStorage.AvatarUrl))
                {
                    // 构建MinIO访问URL - 使用固定的127.0.0.1:9000
                    var objectName = fileStorage.AvatarUrl.Replace("image/", "");
                    avatarUrl = $"http://127.0.0.1:9000/image/{objectName}";
                }
                else
                {
                    // 使用固定的默认头像地址
                    avatarUrl = DEFAULT_AVATAR_URL;
                }

                // 缓存到Redis，设置1小时过期
                await _redisService.SetStringAsync(cacheKey, avatarUrl, TimeSpan.FromHours(1));
                _logger.LogDebug($"头像URL已缓存到Redis: {userCode}");

                return avatarUrl;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取头像URL失败: {userCode}");
                // 如果出错，返回固定的默认头像
                return DEFAULT_AVATAR_URL;
            }
        }

        /// <summary>
        /// 批量获取用户头像URL
        /// </summary>
        public async Task<Dictionary<string, string>> GetAvatarUrlsByUserCodesAsync(List<string> userCodes)
        {
            var result = new Dictionary<string, string>();
            var uncachedUserCodes = new List<string>();

            try
            {
                // 第一步：从Redis批量获取缓存
                foreach (var userCode in userCodes)
                {
                    var cacheKey = $"avatar:url:{userCode}";
                    var cachedUrl = await _redisService.GetStringAsync(cacheKey);

                    if (!string.IsNullOrEmpty(cachedUrl))
                    {
                        result[userCode] = cachedUrl;
                    }
                    else
                    {
                        uncachedUserCodes.Add(userCode);
                    }
                }

                _logger.LogDebug($"从Redis获取 {result.Count} 个头像URL，需要查询数据库 {uncachedUserCodes.Count} 个");

                // 第二步：查询未缓存的用户头像
                if (uncachedUserCodes.Any())
                {
                    var avatars = await _avatarRepository.GetAvatarsByUserCodesAsync(uncachedUserCodes);

                    foreach (var userCode in uncachedUserCodes)
                    {
                        var avatar = avatars.FirstOrDefault(x => x.Code == userCode);
                        string avatarUrl;

                        if (avatar != null && !string.IsNullOrEmpty(avatar.AvatarUrl))
                        {
                            // 构建MinIO访问URL - 使用固定的127.0.0.1:9000
                            var objectName = avatar.AvatarUrl.Replace("image/", "");
                            avatarUrl = $"http://127.0.0.1:9000/image/{objectName}";
                        }
                        else
                        {
                            avatarUrl = DEFAULT_AVATAR_URL;
                        }

                        result[userCode] = avatarUrl;

                        // 缓存到Redis
                        var cacheKey = $"avatar:url:{userCode}";
                        await _redisService.SetStringAsync(cacheKey, avatarUrl, TimeSpan.FromHours(1));
                    }
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量获取头像URL失败");
                // 如果出错，为所有用户返回固定的默认头像
                foreach (var userCode in userCodes)
                {
                    if (!result.ContainsKey(userCode))
                    {
                        result[userCode] = DEFAULT_AVATAR_URL;
                    }
                }
                return result;
            }
        }

        /// <summary>
        /// 清除用户头像缓存
        /// </summary>
        public async Task ClearAvatarCacheAsync(string userCode)
        {
            try
            {
                var cacheKey = $"avatar:url:{userCode}";
                await _redisService.RemoveAsync(cacheKey);
                _logger.LogDebug($"清除头像缓存: {userCode}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"清除头像缓存失败: {userCode}");
            }
        }

        /// <summary>
        /// 上传用户头像
        /// </summary>
        public async Task<AvatarUploadResult> UploadUserAvatarAsync(string userCode, IFormFile file)
        {
            if (file == null || file.Length == 0)
                return new AvatarUploadResult
                {
                    Success = false,
                    Message = "文件不能为空"
                };

            try
            {
                // 上传到MinIO
                var objectName = await _minioService.UploadFileAsync(file, "image");

                // 构建数据库存储的路径
                var dbAvatarUrl = $"image/{objectName}";
                // 使用固定的127.0.0.1:9000构建完整URL
                var fullAvatarUrl = $"http://127.0.0.1:9000/image/{objectName}";

                // 使用工作单元执行事务
                var (success, message) = await _unitOfWork.ExecuteTransactionAsync(async () =>
                {
                    // 1. 禁用用户的所有旧头像
                    var disabledCount = await _avatarRepository.DisableOldAvatarsAsync(userCode);
                    _logger.LogInformation($"用户 {userCode} 已禁用 {disabledCount} 个旧头像");

                    // 2. 保存新头像到数据库
                    var fileStorage = new AvatarModel
                    {
                        Code = userCode,
                        AvatarUrl = dbAvatarUrl,
                        FileName = file.FileName,
                        FileSize = file.Length,
                        MimeType = file.ContentType,
                        CreatedTime = DateTime.Now,
                        Status = 1
                    };

                    await _repository.AddAsync(fileStorage);
                    _logger.LogInformation($"用户 {userCode} 新头像保存成功，文件名: {file.FileName}");

                }, "上传用户头像事务执行失败");

                if (!success)
                {
                    _logger.LogError($"上传用户头像失败: {userCode}, 错误: {message}");
                    return new AvatarUploadResult
                    {
                        Success = false,
                        Message = $"上传头像失败: {message}"
                    };
                }

                // 清除Redis缓存
                await ClearAvatarCacheAsync(userCode);

                _logger.LogInformation($"用户头像上传成功: {userCode}, 文件: {file.FileName}");

                return new AvatarUploadResult
                {
                    Success = true,
                    Message = "头像上传成功",
                    AvatarUrl = fullAvatarUrl
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"上传用户头像失败: {userCode}");
                return new AvatarUploadResult
                {
                    Success = false,
                    Message = $"上传头像失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 获取默认头像URL
        /// </summary>
        public string GetDefaultAvatarUrl()
        {
            return DEFAULT_AVATAR_URL;
        }
    }
}